import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'models/exchange_card.dart';
import 'pages/EcyCardDetailPage.dart';
import 'pages/EcyExchangeRequestsPage.dart';
import 'service/exchange_service.dart';
import 'widgets/card_grid_item.dart';

class EcyExchangeMarketPage extends StatefulWidget {
  const EcyExchangeMarketPage({super.key});

  @override
  _EcyExchangeMarketPageState createState() => _EcyExchangeMarketPageState();
}

class _EcyExchangeMarketPageState extends State<EcyExchangeMarketPage> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final ExchangeService _exchangeService = ExchangeService();
  bool _hasPermission = false;
  bool _isLoading = true;
  List<ExchangeCard> _marketCards = [];
  List<ExchangeCard> _myCards = [];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _checkPermissionAndLoadData();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  Future<void> _checkPermissionAndLoadData() async {
    setState(() => _isLoading = true);
    try {
      final hasPermission = await _exchangeService.checkExchangePermission();
      setState(() => _hasPermission = hasPermission);
      if (hasPermission) {
        await Future.wait([
          _loadMarketCards(),
          _loadMyCards(),
        ]);
      }
    } catch (e) {
      print('Error checking permission: $e');
    } finally {
      setState(() => _isLoading = false);
    }
  }

  Future<void> _loadMarketCards() async {
    try {
      final cards = await _exchangeService.getMarketCards();
      setState(() => _marketCards = cards);
    } catch (e) {
      print('Error loading market cards: $e');
    }
  }

  Future<void> _loadMyCards() async {
    try {
      final cards = await _exchangeService.getMyExchangeCards();
      setState(() => _myCards = cards);
    } catch (e) {
      print('Error loading my cards: $e');
    }
  }

  Widget _buildLockedContent() {
    return Container(
        color: const Color(0xFFF5F5F5),
        child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset('assets/images/locked@2x.png',width: 40,height: 40,),
          const SizedBox(height: 16),
          Text(
            '购买盲盒后解锁互换集市\n开启您的交换之旅',
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Colors.grey[600],
              fontFamily: "PingFang SC",
              fontWeight: FontWeight.w500,

              fontSize: 14,
              height: 1.5,
            ),
          ),
          const SizedBox(height: 32),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 24),
            width: 180.w,
            child: OutlinedButton(
              onPressed: () {
                // TODO: 实现购买逻辑
              },
              style: OutlinedButton.styleFrom(
                backgroundColor: const Color(0xFFF5F5F5),
                // foregroundColor: Colors.grey,
                padding: const EdgeInsets.symmetric(vertical: 12),
                side: const BorderSide(
                  color: Colors.grey,
                  width: 1.2,
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(40),
                ),
              ),
              // ElevatedButton.styleFrom(
              //   backgroundColor: Colors.white,
              //   foregroundColor: Colors.grey,
              //   padding: const EdgeInsets.symmetric(vertical: 12),
              //   shape: RoundedRectangleBorder(
              //     borderRadius: BorderRadius.circular(24),
              //   ),
              // ),
              child: const Text(
                '去购买',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.black,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMarketContent() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_marketCards.isEmpty) {
      return const Center(
        child: Text(
          '暂无可交换的卡片',
          style: TextStyle(
            color: Colors.grey,
            fontSize: 16,
          ),
        ),
      );
    }

    return GridView.builder(
      padding: const EdgeInsets.all(16),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        mainAxisSpacing: 16,
        crossAxisSpacing: 16,
        childAspectRatio: 0.75,
      ),
      itemCount: _marketCards.length,
      itemBuilder: (context, index) {
        final card = _marketCards[index];
        return CardGridItem(
          card: card,
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => EcyCardDetailPage(card: card),
              ),
            );
          },
        );
      },
    );
  }

  Widget _buildMyExchangeContent() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_myCards.isEmpty) {
      return const Center(
        child: Text(
          '暂无上架交换的卡片',
          style: TextStyle(
            color: Colors.grey,
            fontSize: 16,
          ),
        ),
      );
    }

    return GridView.builder(
      padding: const EdgeInsets.all(16),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        mainAxisSpacing: 16,
        crossAxisSpacing: 16,
        childAspectRatio: 0.75,
      ),
      itemCount: _myCards.length,
      itemBuilder: (context, index) {
        final card = _myCards[index];
        return CardGridItem(
          card: card,
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => EcyExchangeRequestsPage(),
              ),
            ).then((value) {
              if (value == true) {
                _loadMyCards(); // 刷新我的卡片列表
              }
            });
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      // decoration: BoxDecoration(
      //   color: const Color(0xFFF5F5F5),
      //   borderRadius: BorderRadius.circular(16),
      // ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // const SizedBox(height: 12),
           Container(
              width: MediaQuery.of(context).size.width,
              height: 30,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(16),
                color: Colors.white,
              ),
              child: IconButton(
                icon: const Icon(CupertinoIcons.chevron_compact_down, color: Colors.black),
                onPressed: () => Navigator.of(context).pop(),
              ),
            ),
          // 标题栏
          Container(
            height: 48,
            alignment: Alignment.center,
            decoration: const BoxDecoration(
              color: Colors.white,
              // borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
            ),
            child: const Text(
              '互换集市',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Colors.black,
              ),
            ),
          ),
          // 内容区
          Flexible(
            child: Container(
              color: const Color(0xFFF5F5F5),
              child: _buildMarketContentBody(),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMarketContentBody() {
    // if (!_hasPermission) {
    //   return _buildLockedContent();
    // }
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }
    // if (_marketCards.isEmpty) {
    //   return Center(
    //     child: Column(
    //       mainAxisAlignment: MainAxisAlignment.center,
    //       children: [
    //         Image.asset(
    //           'assets/images/empty_market.png',
    //           width: 120,
    //           height: 120,
    //         ),
    //         const SizedBox(height: 16),
    //         const Text(
    //           '互换集市里什么都没有~',
    //           style: TextStyle(
    //             color: Colors.grey,
    //             fontSize: 16,
    //           ),
    //         ),
    //       ],
    //     ),
    //   );
    // }
    return Container(
      color: const Color(0xFFF5F5F5),
      child: EcyCardDetailPage(),
    );
  }
}
